﻿using System;
using System.Collections.Generic;
using System.Web;
using Jint;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace Htmlx
{
    public class HtmlxHandler : IHttpHandler
    {
        public HtmlxHandler(JintEngine engine)
        {
            this.engine = engine;
        }

        JintEngine engine;

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            engine.Run("window.location='file://" + context.Request.PhysicalPath.Replace('\\', '/') + "';");
            //engine.Run(envjs.sizzle);
            if (!string.IsNullOrEmpty(context.Request.PathInfo))
                context.Response.Write(engine.CallFunction(context.Request.PathInfo.Substring(1)));
            else
            {
                var html = engine.Run(@"
                var scripts=document.getElementsByTagName('script');
                for(var i=0;i<scripts.length; i++)
                {
                    var script = scripts[i];
                    var runat = script.getAttribute('runat'); 
                    if (runat && runat != 'server') {
                        script.removeAttribute('runat');
                    }
                    if (runat == 'server') {
                        script.parentNode.removeChild(script);
                    }
                }
                var head=document.getElementsByTagName('head')[0];

                if(System.IO.Directory.Exists(Context.Server.MapPath('~/App_Themes/'))){
                    for(var file in System.IO.Directory.GetFiles(Context.Server.MapPath('~/App_Themes/') + Theme, '*.css'))
                    {
                        var link=document.createElement('link');
                        link.setAttribute('rel', 'stylesheet');
                        link.setAttribute('type', 'text/css');
                        link.setAttribute('href', ResolveUrl(file));
                        head.appendChild(link);
                    }
                    }
                return document.innerHTML;");
                context.Response.Write(html);
            }
        }

        #endregion
    }
}
